﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using QunYing.Common;
using System.ServiceModel;

namespace Communicate
{
    public partial class MainForm : Form
    {
        SerialPort sp;
        string filePath = Application.StartupPath + @"\MsgInfo.txt";
        public MainForm()
        {
            InitializeComponent();
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            foreach (var v in ports)
                this.comboBox1.Items.Add(v);
            if (ports.Length > 0)
                this.comboBox1.SelectedIndex = 0;
        }

        protected override void OnLoad(EventArgs e)
        {
          
            base.OnLoad(e);
            this.richTextBox1.AppendText("\r\n");
            sp = new SerialPort();
            sp.MessageReceivedEvent += new Action<string>(sp_MessageReceivedEvent);
            this.btn_Start.Text = OpenSerialPort() ? "停止" : "启动";
        }

        private bool OpenSerialPort()
        {
            if (this.comboBox1.Items.Count == 0)
            {
                this.ShowInfo("未找到短信收发设备！", "连接信息", Color.Red);
                this.button1.Enabled = true;
                return false;
            }
            string com = comboBox1.Text.TrimStart("COM".ToCharArray());
            if (sp.OpenSerialPort(uint.Parse(com)))
            {
                //MessageBox.Show("连接短信猫成功……");
                this.ShowInfo("连接短信猫成功……", "连接信息", Color.Green);
                this.button1.Enabled = false;
                return true;
            }
            else
            {
                this.ShowInfo("连接短信猫失败……", "连接信息", Color.Red);
                this.button1.Enabled = true;
                return false;
            }
        }


        string strTemp = "|1#04#8618702893493#STATUS:002800000000000,15828519435;111111110000000;06.2,15.0,+0035,00.0,1109241121,4.1;100111000000000;END#11-09-24 11:23:32";
        // |2#04#8618702893493#START:002800000000000,15828519435;1111111100000000;07.6,08.1,+250,26.5,1109241123,0600,2000,0600,2000,08,1,0730;END#11-09-24 11:24:58
        void sp_MessageReceivedEvent(string obj)
        {
            try
            {
                string[] messages = obj.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string message in messages)
                {
                    ProcessMessage(message);
                }
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message, "程序错误", Color.Red);
            }
        }

       // string strTemp = "1#04#8618702893493#START:002800000000000,15828519435;1111111100000000;07.9,07.8,+250,26.5,1109241216,0600,2000,0600,2000,08,1,0730;END#11-09-24 12:18:58";
        private void ProcessMessage(string msg)
        {
            string[] dataInfo = msg.Split("#".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            try
            {

                if (dataInfo[3].StartsWith("\nSTATUS:"))
                {
                    ProcessRealTimeInfo(dataInfo[2].Trim("86".ToCharArray()),dataInfo);
                }
               else if (dataInfo[3].StartsWith("STATUS:"))
                {
                    ProcessRealTimeInfo(dataInfo[2].Trim("86".ToCharArray()), dataInfo);
                }
                else if (dataInfo[3].StartsWith("\nSTART:"))
                {
                    ProcessConfigInfo(dataInfo, "\nSTART:");
                }
                else if (dataInfo[3].StartsWith("START:"))
                {
                    ProcessConfigInfo(dataInfo, "START:");
                }
                else if (dataInfo[3].StartsWith("\nCONFI:"))
                {
                    ProcessConfigInfo(dataInfo, "\nCONFI:");
                }

                this.ShowInfo(msg, "水族生态", Color.Blue);
            }
            catch (Exception ex)
            {
                this.ShowInfo(msg+"\r\n"+ex.Message, "程序错误", Color.Red);
            }
            finally
            {
                sp.DeleteData(dataInfo[0]);

            }

        }

        QunYing.BLL.ICSA_Device bll_icsa = new QunYing.BLL.ICSA_Device();
        QunYing.BLL.DeviceRealTimeInfo bll = new QunYing.BLL.DeviceRealTimeInfo();
        private void ProcessRealTimeInfo(string icsa,string[] dataInfo)
        {
            string recData = dataInfo[3].TrimStart("\nSTATUS:".ToCharArray());
            recData = recData.TrimStart("STATUS:".ToCharArray());
            QunYing.Model.DeviceRealTimeInfo realInfo = AnalyseSms.GetRealTimeInfo(recData, icsa);
            if (realInfo == null) return;
           
            realInfo.数据接收时间 = DateTime.Parse(dataInfo[4]);
            string telNum = dataInfo[2].TrimStart("86".ToCharArray());
            realInfo.发送号码 = telNum;
            realInfo.设备ID = telNum;
            int temp=  bll.Add(realInfo);
            if (realInfo.告警信息描述 != "无告警信息")
            {
                var vv = bll_icsa.GetModel(realInfo.发送号码);
                IWarnInfoReceived wr = ClientProxyFactory.GetProxy<IWarnInfoReceived>(GlobalInfo.ServiceWarnInfoReceived);
                wr.WarnInfoReceived(temp, vv.所属经销商);
                (wr as ICommunicationObject).Close();
            }
            else
            {
                QunYing.DAL.DeviceRealTimeInfo dal = new QunYing.DAL.DeviceRealTimeInfo();
                dal.UpdataProcessedSatu(realInfo.设备ID,realInfo.数据接收时间.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }

        private void ProcessConfigInfo(string[] dataInfo, string prefixStr)
        {

            string recData = dataInfo[3].TrimStart(prefixStr.ToCharArray());
            QunYing.Model.ICSA_Device configInfo = AnalyseSms.GetICSAConfig(recData, dataInfo[2].Trim("86".ToCharArray()));
            configInfo.配置更改时间 = DateTime.Now;
            string telNum = dataInfo[2].TrimStart("86".ToCharArray());
            configInfo.通信号码 = telNum;
            QunYing.BLL.ICSA_Device bll = new QunYing.BLL.ICSA_Device();
            if (bll.Exists(configInfo.ICSA设备ID))
            {
                bll.Update(configInfo);
            }
            else
            {
                bll.Add(configInfo);
            }
        }


        private void ShowInfo(string str, string strType, Color foreColor)
        {
            int flag = this.richTextBox1.TextLength;
            string temp = "\r\n[信息类型] " + strType + "\r\n";
            temp = temp + "[信息内容] " + str;
            temp = temp + "\r\n[信息时间] " + DateTime.Now.ToString() + "\r\n";
            int tempLength = temp.Length;
            Action action = new Action(() =>
            {
                Color oldColor = richTextBox1.SelectionColor;
                this.richTextBox1.AppendText(temp);
                richTextBox1.SelectionStart = flag;
                richTextBox1.SelectionLength = tempLength;
                richTextBox1.SelectionColor = foreColor;
                richTextBox1.SelectionLength = 0;
                richTextBox1.SelectionStart = this.richTextBox1.TextLength - 1;
                this.richTextBox1.SelectionColor = oldColor;
                this.richTextBox1.ScrollToCaret();
                if (!File.Exists(filePath))
                {
                    FileStream fs = File.Create(filePath);
                    fs.Close();
                }
                StreamWriter sw = File.AppendText(filePath);
                sw.Write(temp);
                sw.Close();
            });
            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
         
            if (this.btn_Start.Text == "停止")
            {
                this.sp.CloseSerialPort();
                this.btn_Start.Text = "启动";
                this.button1.Enabled = true;
            }
            else
            {
                this.btn_Start.Text = OpenSerialPort() ? "停止" : "启动";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.sp_MessageReceivedEvent(strTemp);
            //string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            //foreach (var v in ports)
            //    this.comboBox1.Items.Add(v);
            //if (ports.Length > 0)
            //    this.comboBox1.SelectedIndex = 0;
        }
    }
}
